package crm.base.security;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import crm.system.entity.Agent;
import crm.system.entity.Authority;
import crm.system.entity.Role;
import crm.system.mapper.AgentMapper;

/**
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数.
 * 
 * @author calvin
 */
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private AgentMapper agentMapper;

	/**
	 * 获取用户Details信息的回调函数.
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

		Agent agent = agentMapper.getAgentAuthoritiesByUserName(username);
		if (agent == null) {
			throw new UsernameNotFoundException("User '" + username + "' not found");
		}
		
//		new User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, obtainGrantedAuthorities(agent));
		return new User(agent.getUserName(), agent.getPassword(), obtainGrantedAuthorities(agent));
	}

	/**
	 * 获得用户所有角色的权限集合.
	 */
	private Set<GrantedAuthority> obtainGrantedAuthorities(Agent agent) {
		Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

		Role role = agent.getRole();
		if (role != null) {
			for (Authority authority : role.getAuthorities()) {
				authorities.add(new SimpleGrantedAuthority(authority.getName()));
			}
		}

		return authorities;
	}
}
